using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.XSSF.UserModel;
using RBAC.Interstructrue;
using RBAC.Read.Api.Application.Command.ERP.SalesReport;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesReport
{
    /// <summary>
    /// 导出 开票通知明细 处理器
    /// </summary>
    public class ExportBillingNoticeDetailHandler : IRequestHandler<ExportBillingNoticeDetailCommand, byte[]>
    {
        private readonly RBACDbContext _context;
        public ExportBillingNoticeDetailHandler(RBACDbContext context)
        {
            _context = context;
        }

        public async Task<byte[]> Handle(ExportBillingNoticeDetailCommand request, CancellationToken cancellationToken)
        {
            var query = _context.BillingAccountings
                .AsNoTracking()
                .Where(b => !b.IsDeleted);

            if (!string.IsNullOrWhiteSpace(request.BillCode))
            {
                var key = request.BillCode.Trim();
                query = query.Where(b => b.BillNumber.Contains(key));
            }
            if (!string.IsNullOrWhiteSpace(request.CustomerName))
            {
                var key = request.CustomerName.Trim();
                query = query.Where(b => b.CustomerName.Contains(key));
            }
            if (!string.IsNullOrWhiteSpace(request.TaxNo))
            {
                var key = request.TaxNo.Trim();
                query = query.Where(b => b.TaxId.Contains(key));
            }
            if (request.StartDate.HasValue)
            {
                var sd = request.StartDate.Value.Date;
                query = query.Where(b => b.BillDate >= sd);
            }
            if (request.EndDate.HasValue)
            {
                var ed = request.EndDate.Value.Date.AddDays(1).AddSeconds(-1);
                query = query.Where(b => b.BillDate <= ed);
            }

            var rows = await query
                .OrderByDescending(b => b.BillDate)
                .ThenByDescending(b => b.BillNumber)
                .Select(b => new
                {
                    BillCode = b.BillNumber,
                    BillDate = b.BillDate,
                    CustomerName = b.CustomerName,
                    TaxNo = b.TaxId,
                    BankName = b.BankName,
                    BankAccount = b.ProductCode,
                    AddressPhone = b.AddressPhone,
                    // 税率如需按明细取平均或首行可调整；目前为空/0
                    TaxRate = 0m,
                    InvoiceQty = b.BillingMaterials.Where(m => !m.IsDeleted).Sum(m => (decimal?)m.Quantity) ?? 0m,
                    InvoiceAmount = b.BillingMaterials.Where(m => !m.IsDeleted).Sum(m => (decimal?)m.Amount) ?? 0m
                })
                .ToListAsync(cancellationToken);

            var wb = new XSSFWorkbook();
            var sheet = wb.CreateSheet("开票通知明细");

            var header = new[] { "序号", "开票单号", "单据日期", "客户名称", "税号", "开户行", "账号", "地址电话", "税率", "开票数量", "开票金额" };
            var headerRow = sheet.CreateRow(0);
            for (int i = 0; i < header.Length; i++) headerRow.CreateCell(i).SetCellValue(header[i]);

            int r = 1;
            int idx = 1;
            foreach (var row in rows)
            {
                var rr = sheet.CreateRow(r++);
                rr.CreateCell(0).SetCellValue(idx++);
                rr.CreateCell(1).SetCellValue(row.BillCode ?? string.Empty);
                rr.CreateCell(2).SetCellValue(row.BillDate.HasValue ? row.BillDate.Value.ToString("yyyy-MM-dd") : string.Empty);
                rr.CreateCell(3).SetCellValue(row.CustomerName ?? string.Empty);
                rr.CreateCell(4).SetCellValue(row.TaxNo ?? string.Empty);
                rr.CreateCell(5).SetCellValue(row.BankName ?? string.Empty);
                rr.CreateCell(6).SetCellValue(row.BankAccount ?? string.Empty);
                rr.CreateCell(7).SetCellValue(row.AddressPhone ?? string.Empty);
                rr.CreateCell(8).SetCellValue(row.TaxRate.ToString());
                rr.CreateCell(9).SetCellValue(row.InvoiceQty.ToString());
                rr.CreateCell(10).SetCellValue(row.InvoiceAmount.ToString());
            }

            for (int i = 0; i < header.Length; i++) sheet.AutoSizeColumn(i);

            using var ms = new System.IO.MemoryStream();
            wb.Write(ms);
            return ms.ToArray();
        }

        // no helpers needed after EF projection
    }
}
